package com.project.processes;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.http.HttpServlet;

import org.apache.log4j.xml.DOMConfigurator;

import com.project.bean.FinalProject;
import com.project.bo.FeaturesBO;
import com.project.bo.RoleBO;
import com.project.configuration.ConfigurationProvider;
import com.project.providers.FeaturesProvider;
import com.project.structures.util.FileUtils;
import com.project.structures.util.XMLUtils;
import com.project.structures.xml.UrlRewriterXML;

public class ApplicationInitialize extends HttpServlet  {

	private static final long serialVersionUID = -871279843650239L;
	
	private static final String configFilePath = "properties";
	
	public void init() {	
		
		Properties properties = new Properties();
        try {  
        	properties.load(this.getServletContext().getResourceAsStream(configFilePath + "/application.properties"));  
        } catch (FileNotFoundException ex) {  
        	ex.printStackTrace();  
        } catch (IOException ex) {
            ex.printStackTrace();  
        }
        
        ConfigurationProvider.getInstance().setConfiguration(properties);
        
        DOMConfigurator.configure(ConfigurationProvider.getInstance().getConfiguration().getProperty("file.log4j.path"));
        
        initializeXMLProvider();
        
        initializeExampleJSP();
        
        FileUtils.setFilePath(ConfigurationProvider.getInstance().getConfiguration().getProperty("features.path"));
        
        initializeFeaturesProvider();
        
        initializeFeatures();
        
        initializeRoles();
        
	}
	
	private void initializeXMLProvider() {
		UrlRewriterXML urlRe = new UrlRewriterXML();
		String url = ConfigurationProvider.getInstance().getConfiguration().getProperty("file.urlrewrite.path");

		urlRe = (UrlRewriterXML) XMLUtils.unmarshalFromFile(urlRe, url);
		
		if (urlRe != null) {
			FinalProject.setUrlrewriterNodes(urlRe);
		}
	}
	
	private void initializeFeaturesProvider() {
		FeaturesProvider featProvider = FeaturesProvider.getInstance();
		featProvider.initProvider();
	}
	
	private void initializeExampleJSP() {
		String urlFile = ConfigurationProvider.getInstance().getConfiguration().getProperty("file.example.jsp.path");
		FinalProject.setExampleJSP(FileUtils.readFile(urlFile));
	}
	
	private void initializeRoles() {
		RoleBO.initializeCache();
	}
	
	private void initializeFeatures() {
		FeaturesBO.initializeCache();
	}
	
}
